<?php

namespace app\api\controller;


use app\common\controller\ApiController;
use think\facade\Db;

class Analysis extends ApiController
{
    protected $noNeedLogin = [];
    protected $mustLogin = [];

    //根据主题id查找最后一个任务
    public function getLastTaskByThemeId()
    {
        $params = $this->request->param(); 
        $find = Db::name('jsyc_task_tech_point')->where('find_in_set('.$params['theme_id'].',theme_ids)')->order('create_time desc')->find();
        if($find){
            $this->success('获取成功', $find);
        }else{
            $this->error('获取失败');
        } 
    }

    //提交任务
    public function submitTask()
    {
        $params = $this->request->param();
        $result = false;
        //添加事务
        Db::startTrans();
        try {
            $dayTaskCount = Db::name('jsyc_task')->whereTime('create_time', 'today')->count(); //等于当日任务数量 
            $lastday = str_pad($dayTaskCount + 1, 3, '0', STR_PAD_LEFT); //任务编号 三位数

            $lastModelConfig = Db::name('jsyc_temp_config')->where('id', 1)->field('model_name,model_temperature,data_source')->find();
            $lastModelConfig['keyword_template_id'] = $params['keyword_template_id'];
            $lastModelConfig['create_time'] = time();
            $lastModelConfig['update_time'] = time();
            $lastModelConfig['delete_time'] = 0;
            $lastModelConfig['no'] = date('Ymd') . '-' . $lastday; //任务编号
            //保存任务
            $result = Db::name('jsyc_task')->insertGetId($lastModelConfig);
            if (!$result) {
                // throw new \Exception('提交失败');
                Db::rollback(); 
                $this->error('提交失败');
            }
            Db::name('jsyc_temp_config')->where('id', 1)->update(['keyword_template_id' => $params['keyword_template_id']]);
           
            $taskDetail = $this->getTaskDetail($result); 
            $keywordTemplate = Db::name('jsyc_keyword_template')->where('id', $taskDetail['keyword_template_id'])->find(); 
            $restTask = [
            'model_name' => $lastModelConfig['model_name'], 
            'model_temperature' => $lastModelConfig['model_temperature'],
            'keyword_template_name' => $keywordTemplate['name'],
            'keyword_template_content' => $keywordTemplate['data_demo'],  
            'taskId' => $result,
            'title' => '任务#'.$lastModelConfig['no'],
            ]; 
            $modelRst = $this->requestTaskAnalysis($restTask, $result); 

            if (!$modelRst) {
                Db::rollback(); 
                $this->error('提交失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功', $restTask);
    }

    //请求任务分析结果
    public function requestTaskAnalysis($params, $taskId)
    { 
        // 使用 PHP cURL 调用外部接口获取分析结果
        $url = env('MODEL.apiUrl') . 'v1/workflows/run';
        $token = env('MODEL.modeToken');
        $payload = json_encode([
            'inputs' => $params,
            'response_mode' => 'blocking',
            'user' => 'abc-123'
        ]);

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30 * 60, // 30 分钟超时
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $token,
            ],
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
        ]);

        $body = curl_exec($ch);
        $err = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($err) {
            // echo $err;exit;
            // $this->error('请求失败：' . $err);
            return false;
        }

        $result = json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            // echo json_last_error_msg();exit;
            // $this->error('响应解析失败：' . json_last_error_msg());
            return false;
        }
        //更新任务状态 
        try { 
            
            $oriData =  isset($result['data']) ? $result['data'] : [];
            $outputs = isset($result['data']['outputs']['result']) ? $result['data']['outputs']['result'] : [];
            $taskInfo = $outputs['taskInfo'];
            $updateParams = ['state'=>1,'model_outputs' => json_encode($oriData)];
            if ($taskInfo['status'] == '已完成'){ 
                $updateParams['state'] = 2;
                $updateParams['complete_time'] = $oriData['finished_at'] ? $oriData['finished_at'] : time();
            }
            Db::name('jsyc_task')->where('id', $taskId)->update($updateParams);
             
            // file_put_contents('task_analysis.log', json_encode($outputs) . PHP_EOL, FILE_APPEND);
            // 保存技术点
            $techPoints = $outputs['techPoints'];
            if (is_array($techPoints) && count($techPoints) > 0) {
                foreach ($techPoints as $techPoint) { 
                    $temp_temp = [];
                    $temp_temp['task_id'] = $taskId;
                    $temp_temp['tech_point_id'] = $techPoint['techPoint']['techPointId'];
                    $temp_temp['tech_point_name'] = $techPoint['techPoint']['techPointName'];
                    $temp_temp['first_theme_id'] = $techPoint['techPoint']['theme']['firstLevelThemeId'];
                    $temp_temp['first_theme_name'] = $techPoint['techPoint']['theme']['firstLevelThemeName'];
                    $temp_temp['second_theme_id'] = $techPoint['techPoint']['theme']['secondLevelThemeId'];
                    $temp_temp['second_theme_name'] = $techPoint['techPoint']['theme']['secondLevelThemeName'];
                    $temp_temp['tech_development_prediction'] = json_encode($techPoint['techPoint']['techDevelopmentPrediction']);
                    $temp_temp['create_time'] = time();
                    $temp_temp['update_time'] = time();
                    $temp_temp['delete_time'] = 0;
                    Db::name('jsyc_task_tech_point')->insert($temp_temp);
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();exit;
            return false;
        }
        return true;
    }
 

    //根据任务id查询任务详情
    public function getTaskDetail($task_id)
    {
        $find = Db::name('jsyc_task')->where('id', $task_id)->find();
        return $find;
    }
    

    //保存配置
    public function saveConfig()
    {
        $params = $this->request->param();
        $params['update_time'] = time();
        $result = Db::name('jsyc_temp_config')->where('id', 1)->update($params);
        if ($result) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }

    //查找最后一次模型配置
    public function getLastModelConfig()
    {
        $lastModelConfig = Db::name('jsyc_temp_config')->where('id', 1)->find();
        $this->success('获取成功', $lastModelConfig);
    }

    //添加关键词模板
    public function addKeywordTemplate()
    {
        $params = $this->request->param();
        //data_demo 反转义
        if (isset($params['data_demo'])) {
            $params['data_demo'] = htmlspecialchars_decode($params['data_demo']);
        }
        $params['create_time'] = time();
        $params['update_time'] = time();
        $params['delete_time'] = 0;
        $result = Db::name('jsyc_keyword_template')->insert($params);
        if ($result) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    //关键词模板
    public function getKeywordTemplateList()
    {
        $keywordTemplateList = Db::name('jsyc_keyword_template')->where(['delete_time' => 0])->order('create_time', 'desc')->select();
        $this->success('获取成功', $keywordTemplateList);
    }

    //技术主题列表
    public function getThemeList()
    {
        $themeList = Db::name('jsyc_technical_theme')->where(['delete_time' => 0])->order('create_time', 'desc')->select();
        //数据转树形结构 parent_id 
        $themeList = $this->buildTree($themeList, 'id', 'parent_id');
        $this->success('获取成功', ['themeList' => $themeList]);
    }

    // 数据转树形结构
    protected function buildTree($data, $pk = 'id', $pid = 'parent_id', $children = 'children', $root = 0)
    {
        $tree = [];
        foreach ($data as $item) {
            if ($item[$pid] == $root) {
                $tree[] = $item;
            }
        }
        foreach ($tree as $key => $item) {
            $tree[$key][$children] = $this->buildTree($data, $pk, $pid, $children, $item[$pk]);
        }
        return $tree;
    }
}
